
/**		
 * 
 *	uk.co.lmfm.guppy.controller.UpdateFlexSDKCommand
 *	
 *	@version 1.00 | Jan 29, 2010
 *	@author Justin Windle
 *  
 **/
 
package uk.co.lmfm.guppy.controller 
{
	import uk.co.lmfm.guppy.application.enum.ApplicationConstants;
	import uk.co.lmfm.guppy.model.AdobeOSProxy;
	import uk.co.lmfm.guppy.model.SettingsProxy;
	import uk.co.lmfm.guppy.model.vo.AlertVO;
	import uk.co.lmfm.guppy.model.vo.AppStateVO;
	import uk.co.lmfm.guppy.model.vo.FlexSDKVO;
	import uk.co.lmfm.guppy.model.vo.SettingsVO;
	import uk.co.lmfm.guppy.view.ProjectMediator;
	import uk.co.lmfm.guppy.view.UpdateMediator;

	import org.osflash.thunderbolt.Logger;
	import org.puremvc.as3.multicore.interfaces.ICommand;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.command.SimpleCommand;

	import flash.filesystem.File;

	/**
	 * UpdateFlexSDKCommand
	 */
	public class UpdateFlexSDKCommand extends SimpleCommand implements ICommand 
	{
		override public function execute(notification : INotification) : void
		{
			super.execute(notification);
			
			var adobeProxy : AdobeOSProxy = facade.retrieveProxy(AdobeOSProxy.NAME) as AdobeOSProxy;
			var settingsProxy : SettingsProxy = facade.retrieveProxy(SettingsProxy.NAME) as SettingsProxy;
			var settings : SettingsVO = settingsProxy.readSettings();
			var appState : AppStateVO = settingsProxy.readAppState();
			
			var config : XML = settingsProxy.readConfig();
			var sdks : XMLList = config..sdk;
			var current : Array = appState.sdks.split(",");
			var queue : Vector.<FlexSDKVO> = new Vector.<FlexSDKVO>();
			
			Logger.info("Currently installed SDKs: " + current);
			
			var exists : Boolean;
			var downloaded : Boolean;
					
			for (var i : int = 0;i < sdks.length();i++) 
			{
				exists = new File().resolvePath(settings.libraryPath).resolvePath("SDK").resolvePath(sdks[i].@id).exists;
				downloaded = current.indexOf(String(sdks[i].@url)) != -1;
				
				if(!exists || !downloaded)
				{
					var sdk : FlexSDKVO = new FlexSDKVO();
							
					sdk.id = sdks[i].@id;
					sdk.url = sdks[i].@url;
					sdk.path = sdks[i].@path;
							
					queue.push(sdk);
				}
			}
					
			if(queue.length > 0)
			{
				adobeProxy.downloadSDKs(queue, settings.libraryPath);
				sendNotification(ApplicationConstants.CHANGE_VIEW, UpdateMediator.NAME);
				sendNotification(ApplicationConstants.DISABLE_MENU);
			}
			else
			{
				Logger.info("Library up to date, starting app");
				
				var afterUpdate : Boolean = Boolean(notification.getBody());
				
				if(afterUpdate)
				{
					var alert : AlertVO = new AlertVO();
				
					alert.title = "Guppy is now up to date!";
					alert.message = "Guppy is in sync with the Guppy repository and all required SDKs are installed. Have fun.";
					alert.label = "OK";
				
					sendNotification(ApplicationConstants.SHOW_ALERT, alert);
				}
				
				sendNotification(ApplicationConstants.CHANGE_VIEW, ProjectMediator.NAME);
			}
		}
	}
}
